package com.iqiyi.pps.epg.web.timer;

import com.iqiyi.pps.epg.core.model.channel.ChannelLog;
import com.iqiyi.pps.epg.core.model.control.PlatformControl;
import com.iqiyi.pps.epg.core.model.control.ProgramPlatformControl;
import com.iqiyi.pps.epg.core.model.program.ProgramData;
import com.iqiyi.pps.epg.core.model.stream.LiveChannelStream;
import com.iqiyi.pps.epg.core.service.broadcast.BroadcastControlService;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.service.notifymail.NotifyMailServiceImpl;
import com.iqiyi.pps.epg.core.service.program.ISnapAsyncService;
import com.iqiyi.pps.epg.core.service.program.ProgramService;
import com.iqiyi.pps.epg.core.service.stream.LiveChannelStreamService;
import com.iqiyi.pps.epg.core.utils.Constants;
import com.iqiyi.pps.epg.core.utils.DateTimeUtil;
import com.iqiyi.pps.epg.core.utils.MailContentUtil;
import com.iqiyi.pps.epg.core.utils.SendMailUtils;
import com.iqiyi.pps.epg.core.utils.mail.MailConstant;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/7/13.
 */
public class AutoProgramStartTimeCheckTrigger {

    private static final Logger logger = LoggerFactory.getLogger(AutoProgramStartTimeCheckTrigger.class);

    @Autowired
    private ProgramService programService;
    @Autowired
    private ISnapAsyncService snapAsyncService;
    @Autowired
    private LiveChannelStreamService liveChannelStreamService;
    @Autowired
    private BroadcastControlService broadcastControlService;
    @Autowired
    private NotifyMailServiceImpl notifyMailService;
    @Autowired
    private ChannelService channelService;

    public void task() {
        logger.info("[AutoProgramStartTimeCheckTrigger][start]");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        long startTime = calendar.getTimeInMillis();
        calendar.add(Calendar.MINUTE, 3);
        calendar.set(Calendar.SECOND, 59);
        long endTime = calendar.getTimeInMillis();
        List<ProgramData> programDataList = programService.checkListQuery(startTime, endTime,false);
        if (programDataList == null) {
            return;
        }
        logger.info("[AutoProgramStartTimeCheckTrigger][programListSize={}]", programDataList.size());
        for (ProgramData programData : programDataList) {
            long qipuId = programData.getQipuId();
            long fatherId = programData.getFatherId();
            long programId = programData.getId();
            long startPlayTime = programData.getStartPlayTime().getTime();
            long stopPlayTime = programData.getStopPlayTime().getTime();
            long noticeStartTime = programData.getNoticeStartTime().getTime();
            List<LiveChannelStream> liveChannelStreamList = liveChannelStreamService.getByFatherId(fatherId);
            //所有码流没有的情况下才表示没有推流
            boolean isLiveStream = false;
            for (LiveChannelStream liveChannelStream : liveChannelStreamList) {
                int status = liveChannelStream.getStatus();
                if (status == LiveChannelStream.STATUS_ACTIVED) {
                    isLiveStream = true;
                    break;
                }
            }

            //没有推流
            if (!isLiveStream) {
                Map<String, String> map = new HashMap<>();
                map.put(MailConstant.P_NAME, programData.getPname());
                map.put(MailConstant.P_QIPU_IDS, programData.getQipuId() + "");
                map.put(MailConstant.P_START_TIME, DateTimeUtil.transLongFormat(programData.getStartPlayTime().getTime()));
                map.put(MailConstant.P_STOP_TIME, DateTimeUtil.transLongFormat(programData.getStopPlayTime().getTime()));

                int delayTimes = programData.getDelayTimes();
                String[] tos = notifyMailService.getTos(fatherId,programData.getId(), MailConstant.TOS_TYPE_FROM_LOG + MailConstant.TOS_TYPE_P_MAIL_TYPE);
                if (delayTimes >= 4) {
                    if (delayTimes >= 5) {
                        continue;
                    }
                    List<ProgramPlatformControl> programPlatformControlList = broadcastControlService.getProgramPlatformControls(programId);
                    int size = programPlatformControlList.size();
                    // 设置节目播控下线
                    if (size > 0) {
                        Map<Integer, ProgramPlatformControl> platformControls = new HashMap<Integer, ProgramPlatformControl>();

                        for (ProgramPlatformControl pc : programPlatformControlList) {
                            pc.setAvailableStatus(ProgramPlatformControl.AVAILABLE_STATUS_DENY);
                            platformControls.put(pc.getPlayPlatform(), pc);
                        }
                        broadcastControlService.setsWithProgram(programId, platformControls);
                    }
                    // 设置节目播控下线
                    List<PlatformControl> platformControlList = broadcastControlService.getPlatformControls(fatherId);
                    size = platformControlList.size();
                    if (size > 0) {
                        for (PlatformControl c : platformControlList) {
                            c.setAvailableStatus(PlatformControl.AVAILABLE_STATUS_DENY);
                        }
                        broadcastControlService.sets(fatherId, platformControlList);
                    }

                    programData.setDelayTimes(delayTimes + 1);
                    programService.editProgramData(programData);
                    snapAsyncService.addProgramTask(programData );
                    //记录日志
                    writeChannelLog(fatherId, Constants.LogType.PROGRAM_OFFLINE.getIndex(), "临时直播节目奇谱ID："  + qipuId + "节目名称：《" + programData.getPname() + "》，节目开始时间：" + DateTimeUtil.transLongFormat(startPlayTime) + "，节目结束时间："+ DateTimeUtil.transLongFormat(stopPlayTime) + "已检测" + programData.getDelayTimes() + "次，未推流，直播节目被下线。");

                    // 节目下线通知编辑
                    map.put(MailConstant.P_DELAY_START_TIME, DateTimeUtil.transLongFormat(startPlayTime));
                    String title = MailContentUtil.getTitleTemplate(MailContentUtil.ContentType.PROGRAM_STARTTIME_OFFLINE_REMIND);
                    String content = MailContentUtil.getContent(MailContentUtil.ContentType.PROGRAM_STARTTIME_OFFLINE_REMIND, map);
                    SendMailUtils.send(title, tos, content);
                    logger.info("[AutoProgramStartTimeCheckTrigger][programId={}][offline]", programId);
                } else {
                    programData.setDelayTimes(delayTimes + 1);
                    Long delayStartPlayTime = startPlayTime + 5 * 60 * 1000;
                    if (startPlayTime == noticeStartTime) {
                        programData.setStartPlayTime(new Timestamp(delayStartPlayTime));
                        programData.setNoticeStartTime(new Timestamp(delayStartPlayTime));
                    } else {
                        programData.setStartPlayTime(new Timestamp(delayStartPlayTime));
                    }
                    ProgramData.calPlayStatus(programData);
                    programService.editProgramData(programData);
                    snapAsyncService.addProgramTask(programData );
                    //记录日志
                    writeChannelLog(fatherId, Constants.LogType.PROGRAM_STARTTIME_DELAY.getIndex(), "临时直播节目奇谱ID："  + qipuId + "节目名称：《" + programData.getPname() + "》，节目开始时间：" + DateTimeUtil.transLongFormat(delayStartPlayTime) + "，节目结束时间："+ DateTimeUtil.transLongFormat(stopPlayTime) + "已检测" + programData.getDelayTimes() + "次，未推流，开始时间自动延后5分钟。");

                    // 时间延后通知编辑
                    map.put(MailConstant.P_DELAY_START_TIME, DateTimeUtil.transLongFormat(delayStartPlayTime));
                    String title = MailContentUtil.getTitleTemplate(MailContentUtil.ContentType.PROGRAM_STARTTIME_DELAY_REMIND);
                    String content = MailContentUtil.getContent(MailContentUtil.ContentType.PROGRAM_STARTTIME_DELAY_REMIND, map);
                    SendMailUtils.send(title, tos, content);
                    logger.info("[AutoProgramStartTimeCheckTrigger][programId={}][delay]", programId);
                }
            }
        }
        logger.info("[AutoProgramStartTimeCheckTrigger][end]");
    }

    private void writeChannelLog(long channelId, int type, String descr) {
        ChannelLog channelLog = new ChannelLog();
        channelLog.setFatherId(channelId);
        channelLog.setType(type);
        channelLog.setDescr(descr);
        channelLog.setUser(Constants.SYSTEM_USER_SIGN);
        channelService.saveLog(channelLog);
    }
}
